package org.zjt.scala.book
import java.io._
import java.net.URL

import scala.collection.mutable.ArrayBuffer
import scala.io.Source
/**
  *
  * Description:
  *   1、文件的读取
  *   2、http url的内容读取
  *   3、二进制、文本文件操作   使用java的 inputStream、reader
  *   4、递归的遍历文件夹中的内容
  *   5、序列化 Serializable 、 SerialVersionUID
  *
  *
  * @author juntao.zhang
  *         Date: 2018-06-28 上午11:28
  * @see
  */
@SerialVersionUID(300L)
class Chapter7 extends Serializable {

  var name:String = "zhangsan"

}

object Chapter7 extends  App {

  lazy val file = Source.fromFile("/Users/juntao.zhang/dev/workspace/myproject/scala-akka-demo/src/main/scala/org/zjt/scala/book/Chapter7.scala","UTF-8")
  var arrayBuffer = ArrayBuffer[String]()
  for(line <- file.getLines()){
    arrayBuffer += line
  }
  println(arrayBuffer.mkString("\n"))


  var array =arrayBuffer.mkString(" ").split(" ")


  val sss = array.map((_,1)).reduceLeft((a,b) =>{
    if(a._1.equals(b._1))  (a._1,a._2 + b._2) else a
  })

  println(sss)


  /**
    * word count
    */
  //  array.map((_,1)).groupBy(a => { a._1 }).foreach(item => println(item._1 ,item._2.map(_._2).sum))
  var wcResult = array.map((_,1)).groupBy(a => { a._1 }).map(item => (item._1 ,item._2.map(_._2).sum))
  for((k,v) <- wcResult){
    println(k,v)
  }



  val url = new URL("https://www.baidu.com")
  var httpResult = Source.fromURL(url)
  println(httpResult.mkString)



  var file2 = new File("/Users/juntao.zhang/dev/workspace/myproject/scala-akka-demo/src")
  var subFileList = file2.listFiles().filter(_.isDirectory).map(_.getAbsolutePath)
  println(subFileList.mkString(","))


  /**
    * 得到所有子文件【递归】
    * @param dir
    * @return
    */
  def subdirs(dir: File): Iterator[File] = {
    val children = dir.listFiles.filter(_.isDirectory())
    /** 递归的调用 subdirs **/
    children.toIterator ++ children.toIterator.flatMap(subdirs _)
  }

  println(subdirs(new File("/Users/juntao.zhang/dev/workspace/myproject/")).mkString(","))



  /**  对象的序列化、反序列化  **/
  var chapter7 = new Chapter7()
  var bos : ByteArrayOutputStream = null
  var oos : ObjectOutputStream = null
  try {
    bos = new ByteArrayOutputStream()
    oos = new ObjectOutputStream(bos)
    oos.writeObject(chapter7)
    oos.flush()
  }catch {
    case e => e.printStackTrace()
  }finally {
    if(null != oos){
      oos.close()
    }
    if(null != bos){
      bos.close()
    }
  }


  var ois : ObjectInputStream = null
  var bis : ByteArrayInputStream = null
  try{
    bis = new ByteArrayInputStream(bos.toByteArray)
    ois = new ObjectInputStream(bis)
    val chapter = ois.readObject().asInstanceOf[Chapter7]
    println(chapter.name)
  }catch {
    case e => e.printStackTrace()
  }finally {
    if(null != ois){
      ois.close()
    }
    if(null != bis){
      bis.close()
    }
  }




}
